#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  util.py
#  
#  Copyright 2013 qiaoliyong <qiaoliyong@localhost.localdomain>
#  
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#  
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#  
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#  
#  

import subprocess
from subprocess import Popen, PIPE, STDOUT
from exception import InValidError
import os
import sys
import traceback
import string
import re
import paramiko

# return a (branch , git_name) pair
# [Frobisher] [build7 PATCH qemu v3 04/14] core: add more cow-bell
# will return build7 qemu
# kinds of sb
def get_branch_gitname(sb):
	try:
		tmp = sb.split('] [')[1].split(' ')
		if tmp[2][-1] == ']':
			tmp[2] = tmp[2][:-1]
	except:
		print "error :%s" % sb
		raise InValidError()
	return (tmp[0], tmp[2])
	
# trim \, / to '_'
# trim \r\n to ' '
def trim(sb):
	r = sb
	r = string.replace(r, '\\' , '_')
	r = string.replace(r, '/' , '_')
	r = string.replace(r, '\r\n', ' ')
	return r

# return if a subject is a cover-letter
# check if sb contain ' 0_' or ' 00_'
def is_cover_letter(sb):
	reg = ' 0*_'
	if re.search(reg, sb):
		return True
	else:
		return False

def exec_command(argv):
    """
    This function executes a given shell command.
    """

    try:
        p = Popen(argv, shell=True, stdout=PIPE, stderr=PIPE)
        out, err = p.communicate()
        rc = p.returncode
    except:
        print traceback.format_exc()

    return (rc, out, err)

def ssh_cmd(host, user, passwd, cmd):
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(hostname = host, username = user, password = passwd)
        stdin, stdout, stderr = client.exec_command(cmd)
        client.close()
        return (stdin, stdout, stderr)

	
if __name__ == "__main__":
	sb = '[Frobisher] [build7 PATCH qemu v3 0_14] core: add more cow-bell'
#	sb = '[Frobisher] [powerkvm PATCH qemu] spapr: fix device nodes handling'
	(a, b) = get_branch_gitname(sb)
	print a
	print b
	print trim(sb)
	print sb
        (rc, out, err) =  exec_command('date')
	print rc
	print out
	print err

	if is_cover_letter(sb):
		print "cover-letter"
	else:
		print "not cover-letter"

	(stdin, stdout, stderr) = ssh_cmd('9.3.189.26','root', 'linux99', 'ls')

	print stdout.readlines()
